package com.twotiger.and.activity.account.repayplan;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.os.Build;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.adapter.DealPlanCalendarAdapter;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.DataList;
import com.twotiger.and.bean.ProjectRepayPlan;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.ListUtils;
import com.twotiger.and.util.PreferencesUtils;
import com.twotiger.and.util.TimeUtils;
import com.twotiger.and.util.ViewUtils;
import com.twotiger.and.view.CalendarView3;
import com.twotiger.and.view.CalendarView3.OnItemClickListener;
import com.view.pulltorefresh.MyListView;
import com.view.pulltorefresh.PullToRefreshBase;
import com.view.pulltorefresh.PullToRefreshBase.OnLastItemVisibleListener;
import com.view.pulltorefresh.PullToRefreshMyListView;

/**
 * 
 * @Description: 
 * 回款计划 
 * @Author gao
 * @Date 2015年8月12日 下午1:56:56
 */
public class RepayPlanCalendarPage extends BaseActivity implements OnClickListener {

    protected static final int GETREPAYMENTSUCCES = 0;
    protected static final int GETREPAYMENTFAIL = 1;

    private PullToRefreshMyListView deal_plan_refresh_list;
    private ArrayList list;
    private int pNum = 1;
    private String TAG_refresh = "DealPlanPage_time";
    private HashMap<String, String> params;
    private TextView sub_title_center_tv;
    private ImageView sub_title_left_bt;
    private DealPlanCalendarAdapter dealPlanCalendarAdapter;

    private String downDateDay; //按下的日期的天的形式
    //    private Date calendarDate; //整个类维护一个date对象

    /**头布局id*/
    private View header_view; //listview的header布局  
    private TextView tv_calendar_year, tv_calendar_month, tv_all_repay_amount, tv_repay_amount,
            calendar_Center;
    private ImageButton calendarLeft, calendarRight;
    private RelativeLayout rl_container;

    private Float[] indexs_pre = new Float[3]; //数组存放待做动画view初始位置坐标x y 和 此view的半径
    private Float[] indexs; //数组存放待做动画view要位移到的位置坐标x y 和 此view的半径

    public static int reqLock = 0; // 保证日历在网络请求过程中，不再次请求网络。同时保证网络请求过程中日历控件不能滑动
    private RelativeLayout rl_calendar_head;
    private CalendarView3 calendar_view;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.deal_plan_calendar_layout, null);
        header_view = inflater.inflate(R.layout.deal_plan_calendar_header_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        deal_plan_refresh_list = (PullToRefreshMyListView) view
            .findViewById(R.id.deal_plan_refresh_list);
        sub_title_center_tv = (TextView) view.findViewById(R.id.sub_title_center_tv);
        sub_title_left_bt = (ImageView) view.findViewById(R.id.sub_title_left_bt);

        findIdForHeader();
        addHeaderForList();

        list = new ArrayList<ProjectRepayPlan>();
        dealPlanCalendarAdapter = new DealPlanCalendarAdapter(RepayPlanCalendarPage.this, list);
        deal_plan_refresh_list.setAdapter(dealPlanCalendarAdapter);
    }

    private void addHeaderForList() {
        ListView lv = deal_plan_refresh_list.getRefreshableView();
        lv.addHeaderView(header_view);
    }

    private void findIdForHeader() {
        rl_calendar_head = (RelativeLayout) header_view.findViewById(R.id.rl_calendar_head);
        tv_calendar_year = (TextView) header_view.findViewById(R.id.tv_calendar_year);
        tv_calendar_month = (TextView) header_view.findViewById(R.id.tv_calendar_month);
        tv_all_repay_amount = (TextView) header_view.findViewById(R.id.tv_all_repay_amount);
        tv_repay_amount = (TextView) header_view.findViewById(R.id.tv_repay_amount);
        calendar_Center = (TextView) header_view.findViewById(R.id.calendar_Center);
        calendarLeft = (ImageButton) header_view.findViewById(R.id.calendarLeft);
        calendarRight = (ImageButton) header_view.findViewById(R.id.calendarRight);
        rl_container = (RelativeLayout) header_view.findViewById(R.id.rl_container);

        calendar_view = (CalendarView3) header_view.findViewById(R.id.calendar_view);
    }

    @Override
    public void onClick(View view) {
        if (ViewUtils.isFastDoubleClick(view)) {
            return;
        }
        switch (view.getId()) {
        case R.id.calendarLeft:
            calendar_view.clickLeftMonth();
            clickLeftButton();
            break;
        case R.id.calendarRight:
            calendar_view.clickRightMonth();
            clickRightButton();
            break;
        case R.id.calendar_Center:
            pNum = 1;
            downDateDay = null;
            indexs = null;
            getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(), "yyyyMM"));
            break;
        case R.id.sub_title_left_bt:
            onBackPress();
            break;
        default:
            break;
        }
    }

    /**
     * 点击左侧按钮或者手势向右滑，切换到上一月
     */
    private void clickLeftButton() {
        if (reqLock == 0) {
            pNum = 1;
            downDateDay = null;
            indexs = null;
            //            calendarDate = TimeUtils.getPreMonthDate(calendarDate);
            getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(), "yyyyMM"));
        }
    }

    /**
     * 点击右侧按钮或者手势向左滑，切换到下一月
     */
    private void clickRightButton() {
        if (reqLock == 0) {
            pNum = 1;
            downDateDay = null;
            indexs = null;
            //            calendarDate = TimeUtils.getNextMonthDate(calendarDate);
            getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(), "yyyyMM"));
        }
    }

    @Override
    protected void setListener() {

        handler = new BaseHandler(this) {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETREPAYMENTSUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        deal_plan_refresh_list.getLoadingLayoutProxy().setLastUpdatedLabel(
                            "最后更新：今天 " + TimeUtils.getFormatDate(" HH:mm"));
                        DataList data = JSONObject.parseObject(result.data, DataList.class);
                        application.setRepayment_timestamp(data.getTimestamp());
                        fillDataForHeader(data);
                        List<String> repaymentDate = JSONArray.parseArray(data.getRepaymentDate(),
                            String.class);
                        calendar_view.setSelectedDate(repaymentDate);
                        reqLock = 0;
                        if (downDateDay != null) {
                            calendar_Center
                                .setBackgroundResource(R.drawable.bg_calendarmonth_gray_shape);
                            calendar_Center.setTextColor(getResources().getColor(color.black));

                            //判断动画终点位置不为空 并且按下日期不为空，就坐动画效果
                            if (indexs != null && downDateDay != null) {
                                ImageView view = new ImageView(RepayPlanCalendarPage.this);
                                view.setImageResource(R.drawable.crilcle_orange);
                                rl_container.addView(view);
                                view.setLayoutParams(new RelativeLayout.LayoutParams(Math
                                    .round(indexs[2]) * 2, Math.round(indexs[2]) * 2));
                                doTranslateAnimation(view, indexs_pre[0], indexs_pre[1], indexs[0],
                                    indexs[1] + ViewUtils.dip2px(RepayPlanCalendarPage.this, 40));
                            }

                            calendar_view.setDownDate(downDateDay);

                        } else {
                            calendar_view.setDownDate(downDateDay);
                            calendar_Center
                                .setBackgroundResource(R.drawable.bg_calendarmonth_orange_shape);
                            calendar_Center.setTextColor(getResources().getColor(color.white));
                        }

                        List<ProjectRepayPlan> repayments = JSONArray.parseArray(data.getList(),
                            ProjectRepayPlan.class);
                        if (!ListUtils.isEmpty(repayments)) {
                            if (repayments.size() < Integer.parseInt(Constants.pageSize)) {
                                deal_plan_refresh_list.changeMyFooterViewContent(false);
                            } else {
                                deal_plan_refresh_list.changeMyFooterViewContent(true);
                            }
                            if (pNum == 1) {
                                dealPlanCalendarAdapter.resetData(repayments);
                            } else {
                                dealPlanCalendarAdapter.addData(repayments);
                            }

                        } else {
                            // showToast("没有数据");
                            if (pNum == 1) {
                                dealPlanCalendarAdapter.clearData(); //显示无数据布局！
                                deal_plan_refresh_list.changeMyFooterViewContent(false);
                            } else {
                                deal_plan_refresh_list.changeMyFooterViewContent(false);
                                dealPlanCalendarAdapter.notifyDataSetChanged();
                            }
                        }
                    } else {
                        showToast(result.codeDesc);
                    }
                    deal_plan_refresh_list.onRefreshComplete();
                    break;
                case GETREPAYMENTFAIL:
                    showToast("网络异常");
                    deal_plan_refresh_list.onRefreshComplete();
                    break;

                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        deal_plan_refresh_list.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

            @Override
            public void onLastItemVisible() {
                String footerContent = ((TextView)deal_plan_refresh_list.getChildviewOfFooterview()).getText().toString();
                if("已无更多项目".equals(footerContent)){
                    return;
                }
                /**
                 * 加载更多数据
                 */
                pNum++;
                if (downDateDay != null) {
                    getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(),
                        "yyyyMMdd"));
                } else {
                    getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(),
                        "yyyyMM"));
                }
            }
        });
        deal_plan_refresh_list
            .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<MyListView>() {
                @Override
                public void onPullDownToRefresh(PullToRefreshBase<MyListView> refreshView) {
                    /**
                     * 刷新数据
                     */
                    pNum = 1;
                    downDateDay = null;
                    indexs = null;
                    getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(),
                        "yyyyMM"));
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<MyListView> refreshView) {
                    /**
                     * 加载更多数据
                     */
                    pNum++;
                    if (downDateDay != null) {
                        getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(),
                            "yyyyMMdd"));
                    } else {
                        getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(),
                            "yyyyMM"));
                    }
                }
            });

        calendar_view.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void OnItemClick(Date downDate, MotionEvent event) {

                pNum = 1;
                downDateDay = getCurrentDateFormatString(downDate, "dd");
                //                calendar_view.setDownDate(downDateDay);

                if (reqLock == 0) {
                    if (indexs != null) {
                        indexs_pre = indexs;
                        indexs_pre[1] = indexs[1]
                                        + ViewUtils.dip2px(RepayPlanCalendarPage.this, 40);
                    } else {
                        //将日历头的位置坐标赋给indexs_pre
                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
                            indexs_pre[0] = (float) (calendar_Center.getLeft() + calendar_Center
                                .getWidth() / 4);
                            indexs_pre[1] = (float) calendar_Center.getBottom();
                        } else {
                            indexs_pre[0] = calendar_Center.getX() + calendar_Center.getWidth() / 4;
                            indexs_pre[1] = calendar_Center.getY();
                        }
                    }
                    indexs = calendar_view.getPositionOfSelected(downDateDay);

                    //                    //判断动画终点位置不为空 并且按下日期不为空，就坐动画效果
                    //                    if (indexs != null && downDateDay != null) {
                    //                        ImageView view = new ImageView(RepayPlanCalendarPage.this);
                    //                        view.setImageResource(R.drawable.crilcle_orange);
                    //                        rl_container.addView(view);
                    //                        view.setLayoutParams(new RelativeLayout.LayoutParams(
                    //                            Math.round(indexs[2]) * 2, Math.round(indexs[2]) * 2));
                    //                        doTranslateAnimation(view, indexs_pre[0], indexs_pre[1], indexs[0],
                    //                            indexs[1] + ViewUtils.dip2px(RepayPlanCalendarPage.this, 40));
                    //                    }

                    getrepaymentlist(getCurrentDateFormatString(downDate, "yyyyMMdd")); //yyyyMMddHHmmssSSS

                }
            }

            @Override
            public void OnFilingToRight() {
                clickLeftButton();
            }

            @Override
            public void OnFilingToLeft() {
                clickRightButton();
            }

        });

        sub_title_left_bt.setOnClickListener(this);
        calendarLeft.setOnClickListener(this);
        calendarRight.setOnClickListener(this);
        calendar_Center.setOnClickListener(this);
    }

    /**
     * 根据返回结果填充header数据
     * 
     * @param data
     */
    protected void fillDataForHeader(DataList data) {
        calendar_Center.setText(TimeUtils.getFormatDate(calendar_view.getCurrentDate(), "yyyy-MM"));
        tv_calendar_year.setText(TimeUtils.getFormatDate(calendar_view.getCurrentDate(), "yyyy")
                                 + "年");
        if (downDateDay != null) {
            tv_calendar_month.setText(TimeUtils.getFormatDate(calendar_view.getCurrentDate(), "MM")
                                      + "月" + downDateDay + "日");
        } else {
            tv_calendar_month.setText(TimeUtils.getFormatDate(calendar_view.getCurrentDate(), "MM")
                                      + "月份");
        }
        tv_all_repay_amount.setText(ArithUtils.coverMoneyComma(data.getSumAmount() + ""));
        tv_repay_amount.setText(ArithUtils.coverMoneyComma(data.getRepaymentAmount() + ""));
    }

    /**
     * 
     */
    public void doTranslateAnimation(final View view, final float rawXPre, final float rawYPre,
                                     final float rawX, final float rawY) {
        if (rawXPre == rawX && rawYPre == rawY) {
            view.setVisibility(View.INVISIBLE);
        } else {
            //初始化  
            TranslateAnimation translateAnimation = new TranslateAnimation(rawXPre, rawX, rawYPre,
                rawY);
            //设置动画时间           
            translateAnimation.setDuration(600);

            view.startAnimation(translateAnimation);
            translateAnimation.setAnimationListener(new AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                    System.out.println(rawXPre + "rawXPre");
                    System.out.println(rawYPre + "rawYPre");
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    view.setVisibility(View.INVISIBLE);
                }
            });
        }
    }

    /**
     * 获取当前日期的年月格式
     * 
     * @return
     */
    protected String getCurrentDateFormatString() {
        return TimeUtils.getFormatDate("yyyyMM");
    }

    /**
     * 指定日期按指定格式输出
     * 
     * @param date
     * @param format
     * @return
     */
    protected String getCurrentDateFormatString(Date date, String format) {
        return TimeUtils.getFormatDate(date, format);
    }

    protected Date getCurrentDate() {
        return TimeUtils.getCurrentDate();
    }

    private void getrepaymentlist(String date) {
        reqLock++;
        params.clear();
        params.put("token", getToken());
        params.put("pageNum", String.valueOf(pNum));
        params.put("pageSize", Constants.pageSize);
        params.put("date", date);
        params.put("timestamp", TimeUtils.getTimeStamp());
        getDate(params, Constants.REPAYMENTQUERY, handler, GETREPAYMENTSUCCES,
            GETREPAYMENTFAIL, true, true, false);
    }

    @Override
    protected void processLogic() {
        initPage();
        initData();

    }

    public void initData() {
        //        calendarDate = getCurrentDate();
        getrepaymentlist(getCurrentDateFormatString(calendar_view.getCurrentDate(), "yyyyMM"));
    }

    private void initPage() {
        // 初始化标题
        params = getParm();
        sub_title_left_bt.setVisibility(View.VISIBLE);
        sub_title_center_tv.setText("还款日历");

    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);

    }
}
